package com.huluobo.a2107monthdemo.cart

import android.content.Intent
import android.util.Log
import android.widget.AdapterView.OnItemClickListener
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2107monthdemo.R
import com.huluobo.a2107monthdemo.base.BaseMVVMFragment
import com.huluobo.a2107monthdemo.databinding.FragmentCartBinding
import com.huluobo.a2107monthdemo.detail.DetailActivity
import com.huluobo.a2107monthdemo.net.Const
import org.w3c.dom.Text

class CartFragment : BaseMVVMFragment<FragmentCartBinding>() {
    private lateinit var viewModel: CartViewModel
    private lateinit var adapter: CartAdapter
    private val cartList = mutableListOf<CartBean>()
    override fun getLayoutId(): Int = R.layout.fragment_cart

    override fun initData() {
        viewModel = ViewModelProvider(this)[CartViewModel::class.java]
        viewModel.getCartList()

        viewModel.getCartListSuccess.observe(this) {
            Log.i("TagA", "cartList:${it.data.size}")
            if (it.code == 200) {
                cartList.clear()
                cartList.addAll(it.data)
                adapter.notifyDataSetChanged()
            }
        }

        viewModel.deleteCartSuccess.observe(this) {
            if (it.code == 200) {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.addSuccess.observe(this) {
            if (it.code == 200) {
                ToastUtils.showLong("购物车数量+1")
            }
        }

        viewModel.removeSuccess.observe(this) {
            if (it.code == 200) {
                ToastUtils.showLong("购物车数量-1")
            }
        }
    }

    override fun initView() {
        dataBinding.cartRv.layoutManager = LinearLayoutManager(requireContext())
        adapter = CartAdapter(cartList)
        dataBinding.cartRv.adapter = adapter

        adapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(requireContext(), DetailActivity::class.java)
            intent.putExtra(Const.PARAM_GOODS_ID, cartList[position].goods_id)
            startActivity(intent)
        }

        dataBinding.cartCbSelectAll.setOnCheckedChangeListener { buttonView, isChecked ->
            cartList.forEach {
                it.isChecked = isChecked
            }
            adapter.notifyDataSetChanged()
        }

        adapter.addChildClickViewIds(
            R.id.cart_item_cb,
            R.id.cart_item_delete,
            R.id.cart_item_iv_add,
            R.id.cart_item_iv_remove
        )

        adapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.cart_item_cb -> {
                    cartList[position].isChecked = !cartList[position].isChecked
                    (adapter.getViewByPosition(position, R.id.cart_item_cb) as CheckBox).isChecked =
                        cartList[position].isChecked
                }

                R.id.cart_item_delete -> {
                    val ids = cartList[position].id.toString()
                    viewModel.deleteCart(ids)
                    cartList.removeAt(position)
                    adapter.notifyItemRemoved(position)
                }

                R.id.cart_item_iv_add -> {
                    cartList[position].count += 1
                    viewModel.addCart(1, cartList[position].goods_id)
                    (adapter.getViewByPosition(position, R.id.cart_item_tv_num) as TextView).text =
                        "${cartList[position].count}"
                }

                R.id.cart_item_iv_remove -> {
                    if (cartList[position].count > 1) {
                        viewModel.removeCart(-1, cartList[position].goods_id)
                        cartList[position].count -= 1
                        (adapter.getViewByPosition(position, R.id.cart_item_tv_num) as TextView).text =
                            "${cartList[position].count}"
                    }
                }
            }
            totalPrice()
        }
        totalPrice()
    }

    private fun totalPrice() {
        var totalPrice = 0
        val checkList = mutableListOf<Boolean>()

        cartList.forEach {
            if (it.isChecked) {
                totalPrice += it.goods_default_price * it.count
            }
            checkList.add(it.isChecked)
        }
        if (checkList.size == 0) {
            dataBinding.cartCbSelectAll.isChecked = false
        } else {
            dataBinding.cartCbSelectAll.isChecked = false !in checkList
        }

        dataBinding.cartTvTotalPrice.text = "总价:￥$totalPrice"
    }
}